<template>
  <div>
    <t-dialog
      header="新增知识点"
      body="水平居中显示的对话框"
      :visible="isshow"
      @close="onReset"
      type="reset"
      :footer="false"
      width="800px"
    >
      <dk-divider style="margin: 10px 0"></dk-divider>
      <t-form
        ref="form"
        :rules="FORM_RULES"
        :data="formData"
        :colon="true"
        reset-type="initial"
        @reset="onReset"
        @submit="onSubmit"
        scrollToFirstError="smooth"
        label-width="140px"
      >
        <t-form-item label="知识点" name="knowledgename">
          <t-input
            v-model="formData.knowledgename"
            :maxlength="20"
            show-limit-number
            placeholder="请输入知识点"
            @enter="onEnter"
          ></t-input>
        </t-form-item>
        <template v-for="(item, index) in formData.answerarr" :key="item.id">
          <dk-divider style="margin: 10px 0"></dk-divider>
          <t-form-item
            :label="'答案' + (index + 1)"
            :name="'answerarr' + index"
          >
            <div style="display: flex; flex-direction: column; width: 100%">
              <div class="delsvgbox">
                <t-button variant="text" @click="deleteitem(item.id)">
                  <icon-svg
                    style="width: 14px; height: 14px"
                    name="icon-shiDelete"
                  ></icon-svg>
                </t-button>
              </div>
              <t-textarea v-model="item.answer" :maxlength="100" placeholder="请输入答案" />
              <div class="huidabox">
                <span>回答后：</span>
                <t-select
                  v-model="item.afteranswer"
                  :options="afteransweroption"
                  style="width: 200px"
                >
                </t-select>
              </div>
            </div>
          </t-form-item>
        </template>

        <t-form-item label="" name="reserveSelectedRowOnPaginate">
          <t-button @click="jia" style="width: 100px">增加新答案</t-button>
        </t-form-item>
        <t-form-item label="答案切换规则" name="reserveSelectedRowOnPaginate">
          <t-radio-group
            v-model="formData.reserveSelectedRowOnPaginate"
            variant="primary-filled"
          >
            <t-radio-button :value="true">顺序</t-radio-button>
            <t-radio-button :value="false">随机</t-radio-button>
          </t-radio-group>
        </t-form-item>

        <t-form-item label="问法" name="questionmethods">
          <t-select
            v-model="formData.questionmethods"
            :options="ScenemsgOptions"
            placeholder="请选择场景信息"
          >
          </t-select>
        </t-form-item>
        <t-form-item label="允许打断" name="interrupt">
          <dk-switch v-model="formData.interrupt"></dk-switch>
        </t-form-item>
        <t-form-item label="意向标签" name="intentionlable">
          <t-select
            v-model="formData.intentionlable"
            :options="ScenemsgOptions"
            placeholder="请选择意向标签"
          >
          </t-select>
        </t-form-item>
        <t-form-item label="自定义标签" name="customizationlable">
          <t-select
            v-model="formData.customizationlable"
            :options="ScenemsgOptions"
            placeholder="请选择自定义标签"
          >
          </t-select>
        </t-form-item>

        <t-form-item class="buttonbut">
          <t-space size="small">
            <t-button theme="default" variant="base" type="reset"
              >取消</t-button
            >
            <t-button theme="primary" type="submit">提交</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>
  
  <script setup>
import { ref, defineProps, reactive, watchEffect } from "vue";
import { nanoid } from "nanoid";
import { MessagePlugin } from "tdesign-vue-next";
import { getcreatetask } from "@/api/callOutTasks/index.js";
import { afteransweroption } from "../formcolumn/knowledgeBase";

const props = defineProps({
  // 默认选中的部门id
  isshow: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["event"]);

let formData = ref({
  knowledgename: "", // 知识点
  reserveSelectedRowOnPaginate: true, // 答案切换规则
  questionmethods: "", // 问法
  interrupt: false, // 是否允许打断
  intentionlable: "", // 意向标签
  customizationlable: "", // 自定义标签
  answerarr0:'',
  answerarr: [
    //答案
    { id: nanoid(), afteranswer: "1", answer: "" },
  ], // 答案
});

const form = ref(null);
// 校验
const FORM_RULES = ref({
  knowledgename: [
    { required: true, message: "请输入知识点", trigger: "change" },
  ],
  questionmethods: [
    { required: true, message: "请输入问法", trigger: "change" },
  ],
  intentionlable: [
    { required: true, message: "请输入意向标签", trigger: "change" },
  ],
  customizationlable: [
    { required: true, message: "请输入自定义标签", trigger: "change" },
  ],
});
watchEffect(() => {
  for (let i = 0; i < formData.value.answerarr.length; i++) {
    let dataobj = ref({});
      dataobj.value = { ...dataobj.value, ...{ ["answerarr" + i]:formData.value.answerarr[i].answer}}
      formData.value = { ...formData.value, ...dataobj.value };
    let obj = ref({});
    obj.value = {
      ...obj.value,
      ...{
        ["answerarr" + i]: [
          {
            validator: (val) => {
              if (formData.value.answerarr[i]?.answer == "") {
                return false;
              } else {
                return true;
              }
            },
            required: true,
            message: "请输入答案",
            trigger: "change",
          },
        ],
      },
    };
  FORM_RULES.value = { ...FORM_RULES.value, ...obj.value };
  }
  
});

// 添加一个答案
const jia = () => {
  //   console.log("jia");
  formData.value.answerarr.push({ id: nanoid(), answer: "", afteranswer: "1" });
  console.log(formData.value);
};
// 删除一个答案
const deleteitem = (id) => {
  console.log(id,'删除id');
  
  if (formData.value.answerarr.length == 1) {
    MessagePlugin.warning("至少保留一个答案");
    return;
  }
  formData.value.answerarr = formData.value.answerarr.filter((item) => {
    return item.id !== id;
  });
};
//取消
const onReset = () => {
  // MessagePlugin.success("重置成功");
  formData.value.answerarr = [{ id: nanoid(), answer: "", afteranswer: "1" }];
  form.value.reset();
  emit("event", false);
};
//提交
const onSubmit = async ({ validateResult, firstError }) => {
  if (validateResult === true) {
    MessagePlugin.success("提交成功");
    // emit('event', false);
    console.log(formData.value,'formData.value提交');
    // const res = await getcreatetask(formData.value);
    // console.log(res);
  } else {
    console.log("Validate Errors: ", firstError, validateResult);
    MessagePlugin.warning(firstError);
  }
};

// 禁用 Input 组件，按下 Enter 键时，触发 submit 事件
const onEnter = (_, { e }) => {
  e.preventDefault();
};
</script>
  
  <style lang="scss" scoped>
.buttonbut {
  display: flex;
  justify-content: space-between;
}
.outtimecla {
  display: flex;
  flex-direction: column;
  .outtimecla_item {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
  }
}
.delsvgbox {
  display: flex;
  justify-content: flex-end;
  //   padding: 8px;
}
.huidabox {
  display: flex;
  align-items: center;
  padding: 8px 0;
  span {
    width: 60px;
    // text-align: right;
  }
  :deep(.t-input) {
    border-color: #ddd;
  }
}
:deep(.t-dialog__ctx .t-dialog) {
  height: 90%;
  overflow-y: scroll;
}
:deep(.t-form-item__control .t-input--error) {
  border-color: inherit; /* 继承默认边框颜色，或设置为你想要的颜色 */
}
</style>
  